package com.dzsw.netty.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class WebSocketClientInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel channel)  {
        ChannelPipeline pipeline = channel.pipeline();
        // 将请求与应答消息编码或者解码为HTTP消息
        pipeline.addLast(new LoggingHandler(LogLevel.INFO));
        pipeline.addLast(new HttpClientCodec());
        pipeline.addLast("aggregator",new HttpObjectAggregator(8192));
        WebSocketClientProtocolConfig config = WebSocketClientProtocolConfig.newBuilder()
                .webSocketUri("ws://localhost:8899/test")
//                .dropPongFrames(false)
//                .subprotocol("protobuf")
                .forceCloseTimeoutMillis(30 * 1000)
                .maxFramePayloadLength(Integer.MAX_VALUE)
                .handshakeTimeoutMillis(30 * 1000)
                .customHeaders(new DefaultHttpHeaders())
                .build();

        pipeline.addLast(new WebSocketClientProtocolHandler(config));
        pipeline.addLast(WebSocketClientHandler.INSTANCE);
    }

}
